package logic

import (
	"ScreenRead/logic/conf"
	"ScreenRead/logic/translate"
	"ScreenRead/util/img"
	"ScreenRead/util/log"
	"encoding/json"
	"github.com/kbinani/screenshot"
	"image"
	"io"
	"net/http"
	"net/url"
	"strings"
	"sync"
)

type ScreenResult struct {
	ScreenShot string      `json:"screen_shot"`
	Result     [2][]string `json:"result"`
}

// ScreenRead 翻译截图文字
func ScreenRead(imgBase64 string) (rt [2][]string) {
	ocrRes := TextReads(imgBase64)

	// 制作翻译列表，并将其组装，避免多次请求
	rt = [2][]string{}
	mtx := &sync.WaitGroup{}
	for _, words := range ocrRes.Words {
		//if strings.ContainsAny(words["words"], "<>\\/") {
		//	continue
		//}

		rt[0] = append(rt[0], words["words"])
		rt[1] = append(rt[1], words["words"])
		mtx.Add(1)
		i := len(rt[1]) - 1
		go func() {
			rt[1][i] = TextTrans(rt[1][i])
			mtx.Done()
		}()
	}
	mtx.Wait()
	if len(rt[0]) == 0 {
		rt = [2][]string{make([]string, 0), make([]string, 0)}
		return rt
	}

	return
}

// ScreenShot 截取图片
func ScreenShot(x0, y0, xt, yt int) (i string) {
	var screenImg *image.RGBA
	var err error
	if xt == 0 || yt == 0 {
		screenImg, err = screenshot.CaptureDisplay(0) // TODO 判断鼠标所在屏幕
	} else {
		screenImg, err = screenshot.Capture(x0, y0, xt, yt)
	}
	if err != nil {
		log.LogObj.Errorln(err)
		return
	}

	i, err = img.ImgToBase64Png(screenImg)
	if err != nil {
		log.LogObj.Errorln(err)
	}
	return
}

// TextReads 识别文本
func TextReads(base64Str string) *OCRRes {
	// 装载识文请求
	payload := strings.NewReader("image=" + url.QueryEscape(base64Str) +
		"&detect_direction=false&paragraph=false&probability=false&language_type=" + conf.Conf.LangMap[conf.Conf.OCRLang].ImgLang)
	client := &http.Client{}
	req, err := http.NewRequest("POST", conf.Conf.OCRUrl, payload)
	if err != nil {
		log.LogObj.Fatalln(err)
	}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Accept", "application/json")

	// 解析识文响应
	res, err := client.Do(req)
	if err != nil {
		log.LogObj.Fatalln(err)
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.LogObj.Fatalln(err)
	}
	ocrRes := &OCRRes{Words: make([]map[string]string, 0)}
	err = json.Unmarshal(body, ocrRes)
	if err != nil {
		log.LogObj.Fatalln(err)
	}

	return ocrRes
}

// TextTrans 翻译文本 V2:使用 deepl
func TextTrans(words string) string {
	trans, err := translate.DeepLTranslate(
		conf.Conf.LangMap[conf.Conf.WordsLang].TextLang,
		conf.Conf.LangMap[conf.Conf.TransLang].TextLang,
		words,
	)

	if err != nil {
		log.LogObj.Errorln(err)
		return ""
	}
	return trans
}

type OCRRes struct {
	Words []map[string]string `json:"words_result"`
	// ...
}

// TextTrans 翻译文本 V1:使用 baidu
//func TextTrans(words string) string {
//	payload := strings.NewReader(`{
//"from":"` + conf.Conf.Lang.TextLang + `",
//"to":"zh",
//"q":"` + words + `"
//}`)
//	client := &http.Client{}
//	req, err := http.NewRequest("POST", conf.Conf.TextTransUrl, payload)
//	if err != nil {
//		log.LogObj.Fatalln(err)
//	}
//	req.Header.Add("Content-Type", "application/json")
//	req.Header.Add("Accept", "application/json")
//	res, err := client.Do(req)
//	if err != nil {
//		log.LogObj.Fatalln(err)
//	}
//	defer res.Body.Close()
//
//	body, err := io.ReadAll(res.Body)
//	if err != nil {
//		log.LogObj.Fatalln(err)
//	}
//
//	transRes := &TextTransRes{
//		Result: struct {
//			TransResult []map[string]string `json:"trans_result"`
//		}{TransResult: make([]map[string]string, 1)},
//	}
//	err = json.Unmarshal(body, transRes)
//	if err != nil {
//		log.LogObj.Fatalln(err)
//	}
//
//	return transRes.Result.TransResult[0]["dst"]
//}
//
//type TextTransRes struct {
//	Result struct {
//		TransResult []map[string]string `json:"trans_result"`
//	} `json:"result"`
//	// ...
//}
